package com.geekstudy.week1;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Week1LoadHello {

    public static void main(String[] args) {
        try {
            // https://base64.us/
            // 5L2g5aW977yMMjAyMQ==
            String targetString = "你好，2021";
            String demoBase = Base64.encodeBase64String(targetString.getBytes("UTF-8"));
            String decodeString = new String(Base64.decodeBase64(demoBase), "UTF-8");
            System.out.println("base64 " + targetString + " is " + demoBase + " 解码后 " + decodeString);

            String filePath = "week1/src/main/java/com/geekstudy/week1/Hello.xlass";
            File file = new File(filePath);
            System.out.println("file:" + file.getAbsolutePath() + " exists:" + file.exists());
            if(file.exists()) {
                // 如果 存在则读取文件流
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available();
                byte[] readByte = new byte[available];
                int readResult = fileInputStream.read(readByte);
                System.out.println("readResult:" + readResult + " available:" + available);
                String fileReadBase = Base64.encodeBase64String(readByte);
                System.out.println("fileBase: " + fileReadBase);

                // 在 main 方法中 Week1LoadHello.class.getResourceAsStream 无法读取文件
                InputStream inputStream = Week1LoadHello.class.getResourceAsStream(filePath);
                if(inputStream != null) {
                    int streamAvailable = inputStream.available();
                    byte[] readStream = new byte[streamAvailable];
                    int streamReadResult = inputStream.read(readStream);
                    String streamBase = Base64.encodeBase64String(readStream);
                    System.out.println("streamReadResult:" + streamReadResult + " streamAvailable:" + streamAvailable);
                    System.out.println("streamBase:" + streamBase);

                    System.out.println("fileBase.equals(streamBase): " + (fileReadBase.equals(streamBase)));
                }

                // ClassLoader 测试
                Week1HelloClassLoad helloLoad = new Week1HelloClassLoad();
                Class<?> loadClass = helloLoad.findClass(filePath);
                System.out.println("loadClass:" + loadClass);
                System.out.println("name:" + loadClass.getName() + " class:" + loadClass.getClass());
                // loadClass:class Hello
                // name:Hello class:class java.lang.Class


            } else {
                System.out.println(" 未找到文件:" + filePath);
            }







        } catch(Exception e) {
            e.printStackTrace();
        }

    }
}
